import { extend, getCurrentPageUrl } from "@/utils/tools"
import useUserStore from "@/store/user"
import useCommonStore from "@/store/common"

const userStore = useUserStore()
const commonStore = useCommonStore()
const _Request = uni.request

interface HttpRequestOptions {
	type?: "GET" | "POST"
	url: string
	data?: Record<string, any>
	extParams?: {
		reject?: boolean
		loading?: boolean
		no_token?: boolean
	}
	header?: Record<string, string>
}

function httpInstance(baseUrl: string) {
	const baseServerUrl = baseUrl

	return {
		get: function (url: string, data: Record<string, any> = {}, extParams = {}) {
			return this.request({
				type: "GET",
				url: url,
				data: data,
				extParams: extParams,
			})
		},
		post: function (url: string, data: Record<string, any> = {}, extParams: Record<string, any> = {}) {
			return this.request({
				type: "POST",
				url: url,
				data: data,
				extParams: extParams,
			})
		},
		request: function (options: HttpRequestOptions) {
			let { type, url, data = {}, extParams = {} } = options
			let postData = extend({}, data)
			postData.under_score = 1

			if (extParams?.no_token) {
			} else {
				postData.frontend_token = userStore.token || ""
			}

			extParams = extend({ reject: false, loading: false }, extParams)

			let showLoading = extParams.loading

			if (!commonStore.showLoading && showLoading) {
				uni.showLoading({
					title: "加载中",
				})
				commonStore.updateShowLoading(true)
			}

			return new Promise((resolve, reject) => {
				_Request({
					url: `${baseServerUrl + url}`,
					method: type || "GET",
					data: postData,
					timeout: 15000,
					dataType: "json",
					header: options.header
						? options.header
						: {
								"Content-Type": "application/x-www-form-urlencoded",
						  },
					success: (res: any) => {
						if (!baseUrl) {
							return resolve(res)
						}
						if (res.statusCode == 200) {
							if (res.data.status == 1) {
								commonStore.updateShowLoading(false)
								resolve(res.data.data)
							} else if (res.data.status == -1001) {
								uni.showToast({
									title: res.data.message,
									icon: "none",
									success: function () {
										if (!commonStore.showLogin) {
											commonStore.updateShowLogin(true)
											uni.showToast({
												title: "您的令牌已过期，请重新登录",
												duration: 2000,
												icon: "none",
												success: () => {
													uni.navigateTo({
														url: `/pages/login/index?return_url=${encodeURIComponent(
															getCurrentPageUrl()
														)}`,
													})
												},
											})
										}
									},
								})
							} else {
								if (extParams.reject === false) {
									uni.showToast({
										title: res.data.message || "接口访问异常",
										duration: 2000,
										icon: "none",
									})
									reject()
								} else {
									reject(res.data)
								}
							}
						} else {
							uni.showToast({
								title: res.data.message || "网络异常",
								duration: 2000,
								icon: "none",
							})
							reject(res)
						}
					},
					fail: (rej) => {
						uni.showToast({
							title: "网络异常",
							duration: 2000,
							icon: "none",
						})
						reject(rej)
					},
					complete: () => {
						showLoading && uni.hideLoading()
					},
				})
			})
		},
	}
}

const $baseApi = httpInstance(import.meta.env.VITE_APP_BASE_URL)
const $lvAppApi = httpInstance(import.meta.env.VITE_APP_LV_APP_URL)

const $jsonApi = httpInstance("")

export { $baseApi, $jsonApi, $lvAppApi }
